import log from "./logger";
import * as fs from 'fs';
import {NodeCO, TrainAllCO} from "./interface";
import config from "./config";
import sender from "./sender";
import * as path from "path";

function formatDateTime(dateString: string) {
    // 分解字符串
    const year = "20" + dateString.substring(0, 2);
    const month = dateString.substring(2, 4);
    const day = dateString.substring(4, 6);
    const hours = dateString.substring(7, 9);
    const minutes = dateString.substring(9, 11);
    const seconds = dateString.substring(11, 13);
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

async function post2(dataStr: string) {
    const lines = dataStr.split(/\r?\n/);
    // log.info('输出结果:', lines[0], lines[1]);
    const nodes: NodeCO[] = []
    let totalWeight = 0
    let totalMaxWeight = 0
    for (let i = 5; i < lines.length - 1; i++) {
        const data = lines[i].split(",");
        for (let j = 0; j < data.length; j++) {
            data[j] = data[j].trim()
        }
        // log.info(data);
        totalWeight += Number.parseFloat(data[4]) || 0;
        totalMaxWeight += Number.parseFloat(data[6]) || 0;
        nodes.push({
            diffWeight: Number.parseFloat(data[7]),
            code: lines[3].split(":")[1].trim() + "-" + data[1],
            lable: null,
            maxNetWeight: Number.parseFloat(data[6]),
            no: data[1],
            sort: Number.parseInt(data[0]),
            speed: Number.parseFloat(data[8]),
            standardTareWeight: null,
            time: null,
            trainCode: lines[3].split(":")[1].trim(),
            carType: data[9],
            weight: Number.parseFloat(data[4]),
            containerNumber1: null,
            containerNumber2: null,
            containerType1: null,
            containerType2: null,
            state: 'Done',
            frontBackDiff: data[10],
            centerDeviation: data[11],
            createTenantId: null,
            createTenantName: null
        })
    }
    const trainCO: TrainAllCO = {
        boxCount: 0,
        code: lines[3].split(":")[1].trim(),
        deviceName: config.deviceName,
        direction: lines[1].split(":")[1].trim() === "-->" ? "Leave" : "Enter",
        endTime: null,
        firstNo: nodes[0].no,
        lastNo: nodes[nodes.length - 1].no,
        name: lines[3].split(":")[1].trim(),
        no: lines[3].split(":")[1].trim(),
        nodes: nodes,
        platformId: config.platformId,
        platformName: config.platformName,
        productName: null,
        senderName: lines[0],
        startTime: null,
        stationName: null,
        time: formatDateTime(lines[3].split(":")[1].trim()),
        totalDiffWeight: totalWeight - totalMaxWeight,
        totalMaxWeight: totalMaxWeight,
        totalNode: Number.parseInt(lines[2].split(":")[1],),
        totalWeight: totalWeight,
        type: "txt",
        wagonType: null,
        createTenantId: null,
        createTenantName: null,
    };
    // log.info("trainCO:", trainCO);

    try {
        await sender.send("trainAll", trainCO);
    } catch (e) {
        log.error("err:", e);
    }
}

async function traverseDirectorySyncSorted(dir: string) {
    // 读取目录中的所有文件/目录并排序
    let files = fs.readdirSync(dir).sort().reverse();
    // 只获取前5个文件或目录
    files = files.slice(0, 3);

    for (const file of files) {
        // 获取完整的文件/目录路径
        const fullPath = path.join(dir, file);
        // 获取文件/目录的状态信息
        const stat = fs.statSync(fullPath);

        if (stat.isDirectory()) {
            // 如果是目录，则递归遍历
            // console.log(`Directory: ${fullPath}`);
            // traverseDirectorySyncSorted(fullPath);
        } else {
            // 如果是文件，就处理文件
            log.info(`File: ${fullPath}`);
            // 同步读取文件内容
            const iconv = require('iconv-lite');
            const data = fs.readFileSync(fullPath);
            // const data = fs.readFileSync(fullPath, 'ascii');
            // 将文件内容按行分割为数组
            const str = iconv.decode(data, 'gbk');
            await post2(str);
        }
    }
}

class ZhangziTrackWorker {
    init() {
        this.collection();
        // setInterval(() => {
        //     this.collection();
        // }, 1000 * 60)
    }

    async collection() {
        try {
            await traverseDirectorySyncSorted('D:\\lw');
        } catch (e) {
            log.error(e)
        }
        // 延时5分钟循环调用
        setTimeout(() => {
            log.info("延时时间到，开始新的采集")
            this.collection();
        }, 1000 * 60 * 5)
    }
}

const zhangziTrackWorker = new ZhangziTrackWorker();
export default zhangziTrackWorker;